package com.zsxb.crm.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zsxb.crm.context.BaseContext;
import com.zsxb.crm.context.StatusContext;
import com.zsxb.crm.dto.BusinessDTO;
import com.zsxb.crm.dto.BusinessPoolDTO;
import com.zsxb.crm.dto.BusinessRecordDTO;
import com.zsxb.crm.dto.ClueGainDTO;
import com.zsxb.crm.enumeration.ResultCodeEnum;
import com.zsxb.crm.exception.BaseException;
import com.zsxb.crm.mapper.BusinessMapper;
import com.zsxb.crm.mapper.RecordMapper;
import com.zsxb.crm.mapper.SysStatusMapper;
import com.zsxb.crm.mapper.UserMapper;
import com.zsxb.crm.pojo.Business;
import com.zsxb.crm.pojo.Clue;
import com.zsxb.crm.pojo.Record;
import com.zsxb.crm.pojo.SysStatus;
import com.zsxb.crm.result.PageResult;
import com.zsxb.crm.service.BusinessService;
import com.zsxb.crm.vo.RecordVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
public class BusinessServiceImpl implements BusinessService {
    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private SysStatusMapper sysStatusMapper;
    @Autowired
    private RecordMapper recordMapper;
    @Autowired
    private UserMapper userMapper;

    //商机分页查询
    @Override
    public PageResult pageQuery(BusinessDTO businessDTO) {
        PageHelper.startPage(businessDTO.getPageNum(), businessDTO.getPageSize());
        //处理数据
        if (businessDTO.getParams() != null) {
            String beginCreateTime = businessDTO.getParams().get("beginCreateTime").toString();
            String endCreateTime = businessDTO.getParams().get("endCreateTime").toString();
            businessDTO.setBeginCreateTime(beginCreateTime);
            businessDTO.setEndCreateTime(endCreateTime);
        }
        log.debug("参数:{}", businessDTO);
        Page<Business> businesses = businessMapper.pageQuery(businessDTO);
        return new PageResult(businesses.getTotal(),businesses.getResult(),null);
    }
    @Override
    public PageResult poolPageQuery(BusinessPoolDTO businessPoolDTO) {
        PageHelper.startPage(businessPoolDTO.getPageNum(), businessPoolDTO.getPageSize());
        if (businessPoolDTO.getParams() != null) {
            String beginCreateTime = businessPoolDTO.getParams().get("beginCreateTime").toString();
            String endCreateTime = businessPoolDTO.getParams().get("endCreateTime").toString();
            businessPoolDTO.setBeginCreateTime(beginCreateTime);
            businessPoolDTO.setEndCreateTime(endCreateTime);
        }
        businessPoolDTO.setStatus(StatusContext.KICK_OUT.toString());
        Page<Business> businesses =  businessMapper.poolPageQuery(businessPoolDTO);
        return new PageResult(businesses.getTotal(),businesses.getResult(),null);
    }

    //根据id查询商机
    @Override
    public Business getById(Long businessId) {
        return businessMapper.getById(businessId);
    }

    @Override
    @Transactional
    public void addBusiness(Business business) {
        List<Business> list = businessMapper.findAll();
        String business1 = list.stream().map(Business::getPhone).filter(Objects::nonNull).filter(o -> o.equals(business.getPhone())).findFirst().orElse(null);
        String business2 = list.stream().map(Business::getWeixin).filter(Objects::nonNull).filter(o -> o.equals(business.getWeixin())).findFirst().orElse(null);
        String business3 = list.stream().map(Business::getQq).filter(Objects::nonNull).filter(o -> o.equals(business.getQq())).findFirst().orElse(null);
        log.info("数据检查：{}|{}|{}",business1,business2,business3);
        if (business1!=null||business2!=null||business3!=null){
            throw new BaseException(ResultCodeEnum.THE_DATA_ALREADY_EXISTS);
        }
        business.setFalseCount(StatusContext.FALSE_COUNT);
        business.setRegion(business.getProvinces()+"_"+business.getCity());
        business.setStatus(StatusContext.TO_BE_FOLLOWED_UP.toString());
        //business.setActivityId(BaseContext.getCurrentId());
        business.setOwner(BaseContext.getCurrentId());
        business.setOwnerTime(LocalDateTime.now());
        businessMapper.insert(business);
    }
    @Override
    @Transactional
    public void addBusinessDetail(BusinessRecordDTO dto) {
        Business business = businessMapper.selectById(dto.getBusinessId());
        BeanUtils.copyProperties(dto,business);
        Record record = new Record();
        List<String> CPlist = sysStatusMapper.findComPoint(dto.getKeyItemsArray());
        String keys = CPlist.stream().collect(Collectors.joining(","));
        record.setKeys(keys);
        BeanUtils.copyProperties(dto,record);
        business.setId(Long.valueOf(dto.getBusinessId()));
        business.setStatus(StatusContext.FOLLOW_UP.toString());
        businessMapper.updateById(business);
        recordMapper.insert(record);
    }



    @Override
    public List<RecordVO> findRecordByBusinessId(Long businessId) {
        List<RecordVO> resList = new ArrayList<>();
        List<Record> list = recordMapper.selectByBusinessId(businessId);
        for (Record record : list) {
            List<String> collect = Arrays.stream(record.getKeys().split(",")).collect(Collectors.toList());
            RecordVO recordVO =new RecordVO();
            BeanUtils.copyProperties(record,recordVO);
            recordVO.setKeys(collect);
            resList.add(recordVO);
        }
        return resList;
    }

    @Override
    public void gainBusiness(ClueGainDTO clueGainDTO) {
        List<Business> list = businessMapper.selectByBusinessIds(clueGainDTO.getIds());
        Integer userCount = businessMapper.countWithUserId(clueGainDTO.getUserId());
        if (userCount+clueGainDTO.getIds().size()>5){
            throw new BaseException(ResultCodeEnum.BUSINESS_HAD_COUNT);
        }
        for (Business business : list) {
            business.setStatus(StatusContext.TO_BE_FOLLOWED_UP.toString());
            business.setOwner(BaseContext.getCurrentId());
            business.setBackReasons(null);
            businessMapper.updateById(business);
        }
    }

    @Override
    public void assign(ClueGainDTO business) {
        List<Business> list = businessMapper.selectByBusinessIds(business.getIds());
        Integer userCount = businessMapper.countWithUserId(business.getUserId());
        if (userCount+business.getIds().size()>5){
            throw new BaseException(ResultCodeEnum.BUSINESS_HAD_COUNT);
        }
        String username = userMapper.findUserNameById(business.getUserId());
        for (Business bus : list){
            bus.setOwner(username);
            bus.setStatus(StatusContext.TO_BE_FOLLOWED_UP.toString());
            bus.setOwnerTime(LocalDateTime.now());
            businessMapper.updateById(bus);
        }

    }

    @Override
    public void backSea(Long businessId, Integer reasonValue) {
        Business business = businessMapper.selectById(businessId);
        if (business==null){
            throw new BaseException(ResultCodeEnum.THE_DATA_DOES_NOT_EXIST);
        }
        business.setStatus(StatusContext.KICK_OUT.toString());
        List<SysStatus> byDictType = sysStatusMapper.findByDictType(StatusContext.REASONS_FOR_BUSINESS_REPORTING);
        SysStatus sysStatus = byDictType.stream().filter(o -> o.getDictValue().equals(reasonValue.toString())).findFirst().orElse(new SysStatus());
        business.setBackReasons(sysStatus.getDictLabel());
        business.setOwner(null);
        business.setOwnerTime(null);
        businessMapper.backSea(business);
    }

    /**
     * 分配商机
     *
     * @param business
     */


}
